<template>
  <div class="login-container">
    <div class="login-card">
      <h2 class="login-title">我是员工！</h2>

      <el-form
        :model="form"
        @submit.prevent="onSubmit"
        class="login-form"
        label-position="top"
      >
        <el-form-item
          label="账号"
          prop="eid"
        >
          <el-input
            v-model="form.eid"
            placeholder="请输入工号"
            prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-button
          native-type="submit"
          type="primary"
          class="login-btn"
          :loading="loading"
        >
          登录
        </el-button>
      </el-form>

      <div class="login-footer">
        <router-link
          to="/eregister"
          class="footer-link"
        >
          注册工号
        </router-link>
        <span class="divider">|</span>

        欢迎加入集团

        <span class="divider">|</span>
        <router-link
          to="/clogin"
          class="footer-link"
        >
          客户通道
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { employee_loginAPI } from "@/api/api.js";
import { ElMessage } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import authStore from "@/model/authstore";


export default {
  data() {
    return {
      form: {
        eid: "",
        password: ""
      },
      loading: false
      // 表单验证规则
      // rules: {
      //   eid: [
      //     { required: true, message: '请输入工号', trigger: 'blur' },
      //     { pattern: /^\d{4,10}$/, message: '工号为4-10位数字', trigger: 'blur' }
      //   ],
      //   password: [
      //     { required: true, message: '请输入密码', trigger: 'blur' },
      //     { min: 6, message: '密码长度不少于6位', trigger: 'blur' }
      //   ]
      // }
    };
  },
  components: { User, Lock },
  methods: {
    async onSubmit() {
      if (this.loading) return;

      try {
        // 基础验证
        if (!this.validateForm()) return;

        this.loading = true;

        // 发送登录请求（HTTPS下明文传输安全）
        const res = await employee_loginAPI({
          eid: this.form.eid,
          password: this.form.password // 保持明文，依赖HTTPS加密
        });

        if (res.code === 200) {
          this.handleLoginSuccess(res);
        } else {
          this.handleLoginError(res);
        }
      } catch (error) {
        this.handleNetworkError(error);
      } finally {
        // 无论成功失败都清理表单密码
        this.form.password = "";
        this.loading = false;
      }
    },

    // 表单验证
    validateForm() {
      if (!this.form.eid) {
        ElMessage.warning(" 请输入工号");
        return false;
      }
      if (!this.form.password) {
        ElMessage.warning(" 请输入密码");
        return false;
      }
      return true;
    },

    // 登录成功处理
    handleLoginSuccess(res) {
      // 安全存储用户数据
      const userData = res.data || {};

      const authData = {
        token: res.token,
        user: {
          eid: userData.eid,
          name: userData.name || "员工",
          permission: userData.permission ?? 0,
          status: userData.status ?? 1,
          avatar: userData.image ,
          hireDate: userData.hiredate || new Date().getTime() // 默认值
        }
      };

      authStore.set("auth", authData);



      // 显示欢迎信息
      ElMessage.success(` 欢迎回来，${userData.name || "员工"}`);


      // 根据权限跳转
      this.redirectByPermission(userData.permission);
    },

    // 权限路由跳转
    redirectByPermission(permission) {
      const routeMap = {
        0: "/e0", // 普通员工
        1: "/e1", // 财务权限
        2: "/e2" // 管理权限
      };

      this.$router.push(routeMap[permission] || "/elogin");
    },

    // 业务错误处理
    handleLoginError(res) {
      const errorMap = {
        401: "账号或密码错误",
        403: "账号已被禁用",
        404: "工号不存在"
      };

      ElMessage.error(errorMap[res.code] || res.message || "登录失败");
    },

    // 网络错误处理
    handleNetworkError(error) {
      if (error.code === "ECONNABORTED") {
        ElMessage.error(" 请求超时，请检查网络");
      } else if (!error.response) {
        ElMessage.error(" 无法连接服务器");
      } else {
        const status = error.response.status;
        const errorMap = {
          400: "请求参数错误",
          500: "服务器内部错误"
        };
        ElMessage.error(errorMap[status] || `请求错误(${status})`);
      }
    }
  },
  // 组件销毁时清理敏感数据
  beforeUnmount() {
    this.form.password = "";
  }
};
</script>
 
<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  min-width: 100vh;
  background: linear-gradient(135deg, #bee3dc 0%, rgb(244, 246, 249) 100%);
}

.login-card {
  width: 380px;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.login-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.32);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 500;
}

.login-form {
  margin-top: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #3f4041;
  margin-bottom: 8px;
}

.login-btn {
  width: 100%;
  height: 44px;
  margin-top: 10px;
  font-size: 16px;
  letter-spacing: 2px;
  background-color: rgba(0, 217, 255, 0.919);
  border: 2px;
  box-shadow: 5px 5px 1px 0px rgba(0, 0, 0, 0.08);
}

.login-btn:hover {
  background-color: rgba(50, 226, 249, 0.681);
  /* color: rgba(0, 0, 0, 0.386); */
}

.login-footer {
  margin-top: 25px;
  text-align: center;
  font-size: 14px;
  color: #606266;
  text-decoration: none;
  transition: color 0.3s;
}

.footer-link {
  color: #606266;
  text-decoration: none;
  transition: color 0.3s;
}

.footer-link:hover {
  color: rgba(33, 199, 218, 0.842);
}

/* 修改聚焦时的阴影 */
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px rgba(100, 99, 99, 0.785) inset !important;
}

/* 修改hover状态 */
:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(139, 137, 136, 0.614) inset !important;
}

.divider {
  margin: 0 12px;
  color: #dcdfe6;
}
</style>